<?php
require_once ('./Static/ArrayAssoc.php');

class ArticleEditorModel{
	private $m_db;
	
	//sätter m_db till medskickat mysqli objekt vid instansierande av klassen
	public function __construct(Mysqli $db){
		$this->m_db = $db;
	}
	//returnerar artikelarray baserat på användarid
	public function GetArticleArray($userId){
		$articleArray = array();
		$stmt = $this->m_db->prepare("SELECT `articleId`, `headline`, `date` FROM `article` WHERE `userId`=?;");
		$stmt->bind_param("i", $userId); 
		$stmt->execute();
		$stmt->bind_result($articleId, $headline, $date);
		
		while($stmt->fetch()){
			$articleArray[] = array(ArrayAssoc::ARTICLE_HEADLINE => $headline, ArrayAssoc::ARTICLE_DATE => $date, ArrayAssoc::ARTICLE_ARTICLEID => $articleId);
		}
		return $articleArray;
	}
	//returnerar enskild artikel baserat på användarid och artikelid
	public function GetArticle($articleId, $userId){
		$stmt = $this->m_db->prepare("SELECT `headline`, `article` FROM `article` WHERE `articleId`=? AND `userId`=?;");
		$stmt->bind_param("si", $articleId, $userId); 
		$stmt->execute();
		$stmt->bind_result($headline, $article);
		
		if($stmt->fetch()){
			return array(ArrayAssoc::ARTICLE_HEADLINE => $headline, ArrayAssoc::ARTICLE_DESC => $article);
		}		
		return null;		
	}
	//Om artikelid är satt uppdateras artikel i databas, annars skapas en helt ny artikel
	public function SubmitArticle($headline, $article, $userId, $articleId = null){
		if(!is_null($articleId) && is_numeric($articleId)){
			$stmt = $this->m_db->prepare("UPDATE article SET `headline`=?, `article`=? WHERE `articleId`=? AND `userId`=?;");
			$stmt->bind_param("ssii", $headline, $article, $articleId, $userId); 
			
			If($stmt->execute() == false){
				return false;
			}
			$stmt->close();
			
			return true;			
		}
		$date = date('Y-m-d');
		$stmt = $this->m_db->prepare("INSERT INTO article (`userId`, `headline`, `article`, `date`) VALUES (?, ?, ?, ?);");
		$stmt->bind_param("isss", $userId, $headline, $article, $date); 
		
		If($stmt->execute() == false){
			return false;
		}
		$stmt->close();
		
		return true;
	}
	//tar bort artikel baserat på artikelid och användarid
	public function RemoveArticle($articleId, $userId){
		$stmt = $this->m_db->prepare("DELETE FROM article WHERE `articleId`=? AND `userId`=?;");
		$stmt->bind_param("ii", $articleId, $userId); 
		
		If($stmt->execute() == false){
			return false;
		}
		$stmt->close();
		
		return true;	
	}
}
?>